package Load
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class MixedLoad
	{
		private var loadData:LoadData;
		private var finishFun:Function;
		private var dispLoader:Loader;
		private var dataList:Array;
		private var complete:Function;
		private var progress:Function;
		private var urlLoader:URLLoader;
		public function MixedLoad()
		{
			super();
			createLoader();
		}
		private function createLoader():void
		{
			dispLoader=new Loader();
			dispLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			dispLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			dispLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadComplete);
			
			urlLoader=new URLLoader();
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			urlLoader.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			urlLoader.addEventListener(Event.COMPLETE,loadComplete);
		}
		public static function load(dataList:Array,finishFun:Function,progress:Function=null,complete:Function=null):void
		{
			var loader:MixedLoad=new MixedLoad();
			loader.dataList=dataList;
			loader.complete=complete;
			loader.finishFun=finishFun;
			loader.progress=progress;
			loader.loadNext();
		}
		private function loadNext():void
		{
			if(dataList.length==0)
			{
				if(complete)
				{
					complete();
				}
				return;
			}
			loadData=dataList.shift();
			if(loadData.dataFormat==DataFormat.IMAGE)
			{
				if(loadData.bytes)
				{
					dispLoader.loadBytes(loadData.bytes,loadData.context);
				}
				else
				{
					dispLoader.load(new URLRequest(loadData.url),loadData.context);
				}
			}
			else
			{
				urlLoader.dataFormat=loadData.dataFormat;
				urlLoader.load(new URLRequest(loadData.url));
			}
		}
		private function loadComplete(event:Event):void
		{
			if(loadData.dataFormat==DataFormat.IMAGE)
			{
				loadData.data=dispLoader.content;
			}
			else
			{
				loadData.data=urlLoader.data;
			}
			
			if(finishFun)
			{
				finishFun(loadData);
			}
			
			loadNext();
		}
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			
		}
		private function progressHandler(event:ProgressEvent):void
		{
			if(progress)
			{
				progress(loadData,event.bytesLoaded,event.bytesTotal);
			}
		}
	}
}